package cn.tedu.property_management_system.service.Impl;

import cn.tedu.property_management_system.ex.ServiceException;
import cn.tedu.property_management_system.service.IUploadService;
import cn.tedu.property_management_system.utils.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.sql.rowset.serial.SerialException;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import static cn.tedu.property_management_system.utils.JsonResult.State.BAD_REQUEST;

@Slf4j
@Service
public class UploadServiceImpl implements IUploadService, Constant {
    /**
     * 父文件夹日期格式
     */
    private static final String DATA_FORMAT="/yyyy/MM/";

    /**
     * 以时间戳作为文件名的前缀格式
     */
    private static final String DATA_TIME_FORMAT="yyyyMMddHHmmssSSS";

    @Value("${uploda-file.baseFile}")
    private String baseFile;

    @Value("${uploda-file.allowedTypes.compliant}")
    private ArrayList<String> compliantAllowedTypes;

    @Value("${uploda-file.allowedTypes.repair}")
    private ArrayList<String> repairAllowedTypes;

    @Value("${uploda-file.maxsize.compliant}")
    private long compliantMaxSize;

    @Value("${uploda-file.maxsize.repair}")
    private long repairIconMaxSize;

    @Override
    public String uploadImg(MultipartFile file,String filePreFix) {
        String fullName="";
        try {
            //根据controller传入的文件前缀判断上传文件的类型
            if (COMPLAINT_IMG_FILE_PRE.equals(filePreFix)) {
                fullName=uploadFile(file, compliantAllowedTypes, compliantMaxSize, filePreFix);
            }
            else if (REPAIR_IMG_FILE_PRE.equals(filePreFix)){
                fullName=uploadFile(file, repairAllowedTypes, repairIconMaxSize, filePreFix);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fullName;
    }

    @Override
    public void deleteComplaintImgPic(String name) {
        String parentFileName=baseFile+COMPLAINT_IMG_FILE_PRE+getTimeStamp(DATA_FORMAT)+name;
        log.debug("删除图片的父路径为[{}]",parentFileName);
        File file = new File(parentFileName);
        if (!file.exists())
            throw new ServiceException(BAD_REQUEST,"删除文件不存在");
        file.delete();
    }

    @Override
    public void deleteRepairImgPic(String name) {
        String parentFileName=baseFile+REPAIR_IMG_FILE_PRE+getTimeStamp(DATA_FORMAT)+name;
        log.debug("删除图片的父路径为[{}]",parentFileName);
        File file = new File(parentFileName);
        if (!file.exists())
            throw new ServiceException(BAD_REQUEST,"删除文件不存在");
        file.delete();
    }

    private String uploadFile(MultipartFile file, List<String> contentType, long maxSize, String uploadParentFileName) throws IOException {
        if (file==null||file.isEmpty()){
            throw new ServiceException(BAD_REQUEST,"上传失败,不允许使用空文件作为参数");
        }
        String fileContentType = file.getContentType();
        if (!contentType.contains(fileContentType)){
            throw new ServiceException(BAD_REQUEST,"上传失败,不允许使用"+fileContentType+
                    "类型的文件,被允许的格式有"+contentType.toString());
        }
        if (file.getSize()>(maxSize*1024)){
            throw new ServiceException(BAD_REQUEST,"文件过大,请限制上传文件大小为:"+maxSize/1024+"KB以内");
        }
        String parentFileName=baseFile+uploadParentFileName+getTimeStamp(DATA_FORMAT);
        File parentFile = new File(parentFileName);
        if (!parentFile.exists()){
            parentFile.mkdirs();
        }
        String fileName=getTimeStamp(DATA_TIME_FORMAT);

        String suffix=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String fullName=fileName+suffix;
        File dest=new File(parentFile,fullName);
        log.debug("保存图片的路径为[{}]",dest.getAbsoluteFile());
        file.transferTo(dest);
        return fullName;
    }

    private String getTimeStamp(String format){
        String timeStamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern(format));
        return timeStamp;
    }

}
